/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @Package: com.bccah.modweb.opex.controller
 * @Filename: CommonController.java
 * @Description: TODO(简述该文件的作用)
 * @author: 金鑫智慧
 * @date: 2019年5月5日 下午4:49:09
 * @version: V2.0
 * @Copyright: 2019 www.beonelot.com Inc. All rights reserved.
 * 注意：本内容仅限于重庆金鑫智慧科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
package com.jinxin.platform.cdperprotypay.support;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * TODO(简述该类的作用)提供獲取ip等方法
 * @Classn: CommonController
 * @author: wangpan
 * @date: 2019年5月5日
 */
public class IPUtils {
    private static final Logger logger = LoggerFactory.getLogger(IPUtils.class);

    /**
     *
     * TODO(简述该方法的作用)根據請求的request，獲取請求信息ip
     * @method getIp
     * @return String
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        if (request == null) {
            try {
                throw (new Exception("getIpAddr method HttpServletRequest Object is null"));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                logger.error("error", e);
            }
        }
        String ipString = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
            ipString = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
            ipString = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ipString) || "unknown".equalsIgnoreCase(ipString)) {
            ipString = request.getRemoteAddr();
        }

        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ipString.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ipString = str;
                break;
            }
        }
        return ipString;
    }


    public static JSONObject getAddressByIP(String strIP) {
        JSONObject data = null;
        try {
            URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + strIP);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            JSONObject object = JSON.parseObject(result.toString());
            data = object.getJSONObject("data");

        } catch (Exception e) {
            logger.error("error", e);
        }
        return data;
    }


    /**
     * 获取本机的IP地址（包括ipv4和ipv6）
     * <br>包含回环地址127.0.0.1和0:0:0:0:0:0:0:1
     */
    public static Set<String> getIpAddress() {
        Set<String> ipList = new HashSet<>();
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                //排除虚拟接口和没有启动运行的接口
                if (netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip != null && (ip instanceof Inet4Address || ip instanceof Inet6Address)) {
                            ipList.add(ip.getHostAddress());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ipList;
    }

}
